/*
 *  Copyright 2009 Lucas Nazário dos Santos
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sourceforge.retriever.filter;

import java.util.HashMap;
import java.util.Map;

import net.sourceforge.retriever.fetcher.Resource;

/**
 * <p>
 * Class used to filter URLs that literally match some string.
 * </p>
 */
public class URLLiteralFilter implements Filter {


	private final Map<String, Boolean> patterns = new HashMap<String, Boolean>();

	/**
	 * <p>
	 * Adds a pattern, which is a string that will be used in the filtering process.
	 * </p>
	 * 
	 * <p>
	 * If the URL of a resource literally matches the pattern, then it will be filtered.
	 * </p> 
	 * 
	 * @param pattern The pattern to be used in the filtering process.
	 */
	public void addPattern(final String pattern) {
		this.addPattern(pattern, true);
	}

	/**
	 * <p>
	 * Adds a pattern, which is a string that will be used in the filtering process.
	 * </p>
	 * 
	 * <p>
	 * Depending on the value of the <code>ifMatchAccept</code> parameter, the filter class
	 * will act differently. If the parameter's value is true, than URLs matching the pattern
	 * will be rejected. URLs will otherwise successfully pass the filter if the parameter's
	 * value is false and they match the pattern. 
	 * </p>
	 * 
	 * @param pattern The pattern to be used in the filtering process.
	 */
	public void addPattern(final String pattern, final boolean ifMatchAccept) {
		this.patterns.put(pattern, ifMatchAccept);
	}

	/**
	 * Always return true because the resource has already gone through the
	 * <code>acceptBeforeFetch(String)</code> method.
	 */
	public boolean acceptAfterFetch(final Resource resource) {
		return this.acceptBeforeFetch(resource.getURL().toExternalForm());
	}

	/**
	 * @see net.sourceforge.retriever.filter.Filter#acceptBeforeFetch(String)
	 */
	public boolean acceptBeforeFetch(final String url) {
		if (this.patterns.size() <= 0) return true;
		
		if (this.patterns.keySet().contains(url)) {
			return this.patterns.get(url);
		} else {
			return false;
		}
	}
}